<template>
  <div>
    <!-- 图片上传及文件查看 -->
    <div v-if="model.uploadType === 'img' || model.isDetail" ref="viewer" v-viewer="{filter: filterView}" class="file-content">
      <div v-for="(item, index) in allFileArr" :key="`a${index}`" class="file-item">
        <div v-if="fileType('img', item.filePath)" class="file-item__content">
          <img class="file-item__img" :src="getImgUrl(item.filePath)" alt>
          <div class="file-item__modal">
            <i class="el-icon-zoom-in item" @click="preview(item.filePath)" />
            <download :params="{url: item.filePath, fileName: item.fileName, fileExt: item.fileExtname}">
              <i class="el-icon-download" />
            </download>
            <i v-if="!model.isDetail" class="el-icon-delete" @click="deleteItem(item, index)" />
          </div>
        </div>
        <div v-else class="file-item__content">
          <div>
            <svg-icon v-if="fileType('word', item.filePath)" icon-class="icon-cod" class="svg-icon" />
            <svg-icon v-else-if="fileType('pdf', item.filePath)" icon-class="icon-pdf" class="svg-icon" />
            <svg-icon v-else-if="fileType('excel', item.filePath)" icon-class="icon-xls" class="svg-icon" />
            <div class="file-name">{{ item.fileName }}</div>
            <div class="file-other-bottom">{{ item.updateDatetime ? item.updateDatetime.substring(0, 10): '' }}</div>
          </div>
          <div class="file-item__modal">
            <i v-if="fileType('pdf', item.filePath)" class="el-icon-zoom-in item" @click="preview(item.filePath)" />
            <download :params="{url: item.filePath, fileName: item.fileName, fileExt: item.fileExtname}">
              <i class="el-icon-download" />
            </download>
            <i v-if="!model.isDetail" class="el-icon-delete" @click="deleteItem(item, index)" />
          </div>
        </div>
      </div>
      <div class="file-operation">
        <div v-if="!model.isDetail" class="file-operation__right">
          <el-upload
            :action="action"
            multiple
            :disabled="!!uploadTimes"
            :headers="headers"
            :data="data"
            accept="image/png,image/jpeg"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :show-file-list="false">
            <svg-icon v-if="allFileList.length<10" icon-class="addFile" class="add-file-svg" style="color: #606266;width: 100%;height: 100px;margin: 12% 0" />
          </el-upload>
        </div>
      </div>
    </div>
    <!-- 图片上传及文件查看 -->

    <!-- 文件拖拽上传 -->
    <div v-if="model.uploadType === 'file' && !model.isDetail" ref="viewer" v-viewer="{filter: filterView}" class="drag-file-content">
      <div class="drag-upload-operation">
        <div>
          <el-upload
            drag
            :action="action"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            multiple
            :show-file-list="false">
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <div class="file-list">
        <ul class="el-upload-list el-upload-list--text">
          <li v-for="(item, index) in allFileArr" :key="`b${index}`" class="el-upload-list__item is-success">
            <a class="el-upload-list__item-name">
              <i class="el-icon-document" />
              {{ item.fileName }}
              <i class="el-icon-close" @click="deleteItem(item, index)" />
            </a>
          </li>
        </ul>
      </div>
    </div>
    <!-- 文件拖拽上传 -->
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { isImg, isPdf, isWord, isExcel } from '@/utils/validate'
import Download from './Download'

export default {
  name: 'FileUpload',
  components: {
    Download
  },
  props: {
    model: {
      type: Object,
      default() {
        return {
          title: '',
          visible: false,
          pathList: [],
          fileList: [],
          type: 1,
          key: 0,
          index: 0,
          isDetail: false,
          uploadType: 'img'
        }
      }
    }
  },
  data() {
    return {
      active: 1,
      allFileArr: [],
      allFileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/dfile/file/uploadById/',
      action: process.env.VUE_APP_BASE_API + '/dfile/file/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      data: {
        id: ''
      },
      uploadTimes: 0 // 当前上传的数量   控制loading效果
    }
  },
  computed: {
    imgList() {
      return this.allFileList.filter(item => isImg(item)).map(item => this.getUrl(item))
    }
  },
  watch: {
    'model.pathList'(val) {
      if (val) {
        this.allFileList = [...val]
      }
    },
    'model.fileList'(val) {
      if (val) {
        this.allFileArr = [...val]
      }
    }
  },
  mounted() {
    this.allFileList = [...this.model.pathList]
    this.allFileArr = [...this.model.fileList]
  },
  methods: {
    beforeCloseDialog() {
      this.allFileArr = []
      this.allFileList = []
    },
    fileType(type, url) {
      switch (type) {
        case 'img':
          return isImg(url)
        case 'pdf':
          return isPdf(url)
        case 'word':
          return isWord(url)
        case 'excel':
          console.log(isExcel(url), 889)
          return isExcel(url)
      }
    },
    getImgUrl(item) {
      if (this.fileType('img', item)) {
        return this.getUrl(item)
      }
      //  else if (this.fileType('pdf', item)) {
      //   return (require('@/assets/images/preview-pdf.png'))
      // } else if (this.fileType('word', item)) {
      //   return (require('@/assets/images/preview-word.png'))
      // } else if (this.fileType('excel', item)) {
      //   return (require('@/assets/images/preview-excel.png'))
      // }
    },
    getUrl(item) {
      return (
        process.env.VUE_APP_BASE_API +
        '/dfile/file/download?fileUrl=' +
        item +
        '&access_token=' +
        getToken()
      )
    },
    filterView(image) {
      //  文件为图片才能预览   为excel等类型时 展示的是静态图片 路径中不存在 itps/dfile
      return image.src.includes('itps/dfile')
    },
    preview(item) {
      if (isImg(item)) {
        const idx = this.imgList.indexOf(this.getUrl(item))
        this.$refs.viewer.$viewer.view(idx)
      } else if (isPdf(item)) {
        window.open(`${this.publicPath}/pdf/web/viewer.html?file=${encodeURIComponent(this.getUrl(item))}`, '附件预览')
      } else {
        window.open(this.getUrl(item))
      }
    },
    // download(item) {
    //   window.open(this.getUrl(item))
    // },
    deleteItem(item, index) {
      this.confirmBox('确定删除?').then(() => {
        this.allFileList.splice(index, 1)
        this.allFileArr.splice(index, 1)
        var files = [...this.allFileList]
        var allFileArrs = [...this.allFileArr]
        this.$emit('on-success', files, this.model.type, this.model.key, this.model.index, allFileArrs)
        this.notifiySuccess('删除成功!')
      })
    },
    beforeUpload(file) {
      if (!this.fileType('img', file.name) && !this.fileType('pdf', file.name) && !this.fileType('word', file.name) && !this.fileType('excel', file.name)) {
        this.notifiyError(`上传失败，不支持的文件格式`)
        return false
      }
      if (this.allFileArr.length === 10) {
        this.notifiyError(`上传失败，上传文件数不能超过10个`)
        return false
      }
      this.uploadTimes++
      return true
    },
    uploadSuccess(response, file, fileList) {
      this.uploadTimes--
      if (response.status === 200) {
        if (this.allFileArr.length < 10) {
          this.allFileArr.push({
            bizType: this.model.bizType,
            fielSize: file.size,
            fileExtname: file.name.slice(file.name.lastIndexOf('.') + 1),
            fileName: file.name,
            filePath: response.data,
            fileType: '1' // 1: 图片 2：音视频 3：其他
          })
        }
        if (this.allFileList.length < 10) {
          this.allFileList.push(response.data)
        }
        var files = [...this.allFileList]
        var allFileArrs = [...this.allFileArr]
        this.$emit('on-success', files, this.model.type, this.model.key, this.model.index, allFileArrs)
      } else {
        this.notifiyError(`${file.name}上传失败`)
      }
    },
    uploadError(error, file, fileList) {
      this.uploadTimes--
      if (error) {
        this.notifiyError(`${file.name}上传失败`)
      }
    }
  }
}
</script>
<style lang="scss">
.file-operation {
  display: inline-block !important;
  width: 20%;
  position: relative;
}
.file-content {
  min-height: 300px;
  // max-height: calc(80vh - 170px);
  padding: 10px;
  font-size: 0;
  overflow: auto;
  .file-item {
    display: inline-block;
    width: 20%;
    padding-bottom: 20%;
    position: relative;
  }
  .file-item__content {
    position: absolute;
    left: 5px;
    top: 5px;
    bottom: 5px;
    right: 5px;
    border: 1px solid #d9dde4;
    border-radius: 5px;
    text-align: center;
    overflow: hidden;
    box-shadow: 0 0 4px 1px #d9dde4;
    display: flex;
    align-items: center;
    div {
      width: 100%;
    }
    .file-item__img {
      width: 100%;
      height: 100%;
      vertical-align: middle;
      object-fit: cover;
    }
    &::after,
    .file-item__modal::after {
      content: "";
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
    &:hover .file-item__modal {
      opacity: 1;
    }
    .svg-icon {
      width: 30px;
      height: 35px;
      display: inline-block;
      margin-bottom: 10px;
    }
    .file-name {
      display: -webkit-box;
      padding: 0 12px;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      font-size: 12px;
      line-height: 17px;
    }
    .file-other-bottom {
      margin-top: 10px;
    }
    .file-item__modal {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 5px;
      opacity: 0;
      transition: opacity 0.3s;
      i {
        font-size: 20px;
        color: #fff;
        cursor: pointer;
      }
      .item {
        margin-right: 10px;
      }
      .el-icon-delete {
        margin-left: 10px;
      }
    }
  }
}
.drag-file-content {
  min-height: 300px;
  padding: 10px;
  font-size: 0;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  .file-list {
    padding-left: 5px;
    font-size: 14px;
    .el-icon-close {
      top: 0;
      line-height: 25px;
    }
  }
}
.add-file-svg:hover path{
  fill: #000;
}
</style>
